package com.dreamwhale.machinery.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dreamwhale.machinery.config.DataResult;
import com.dreamwhale.machinery.dao.YxStoreProductAttrValueMapper;
import com.dreamwhale.machinery.entity.YxStoreProduct;
import com.dreamwhale.machinery.entity.YxStoreProductAttrResult;
import com.dreamwhale.machinery.entity.YxStoreProductAttrValue;
import com.dreamwhale.machinery.goods.entity.YxStoreCart;
import com.dreamwhale.machinery.goods.entity.YxStoreOrder;
import com.dreamwhale.machinery.goods.mapper.YxStoreCartMapper;
import com.dreamwhale.machinery.goods.mapper.YxStoreOrderMapper;
import com.dreamwhale.machinery.goods.service.YxStoreCartService;
import com.dreamwhale.machinery.goods.service.YxStoreOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dreamwhale.machinery.pay.ali.server.AliPayService;
import com.dreamwhale.machinery.pay.weChat.server.WeChatPayServer;
import com.dreamwhale.machinery.pay.weChat.utils.WxNotifyParam;
import com.dreamwhale.machinery.service.YxStoreProductService;
import com.dreamwhale.machinery.user.entity.UserShop;
import com.dreamwhale.machinery.user.entity.YxUserAddress;
import com.dreamwhale.machinery.user.mapper.UserShopMapper;
import com.dreamwhale.machinery.user.service.YxUserAddressService;
import com.dreamwhale.machinery.utils.KdApiOrderDistinguish;
import com.dreamwhale.machinery.utils.KdniaoTrackQueryAPI;
import com.dreamwhale.machinery.utils.WorkIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Author
 * @since 2020-05-28
 */
@Service
public class YxStoreOrderServiceImpl extends ServiceImpl<YxStoreOrderMapper, YxStoreOrder> implements YxStoreOrderService {

    @Resource
    private YxStoreCartService yxStoreCartService;
    @Resource
    private YxStoreCartMapper yxStoreCartMapper;

    @Resource
    private YxUserAddressService yxUserAddressService;

    @Resource
    private YxStoreProductService yxStoreProductService;

    @Resource
    private YxStoreOrderMapper yxStoreOrderMapper;

    @Resource
    private YxStoreProductAttrValueMapper yxStoreProductAttrValueMapper;

    @Resource
    private AliPayService aliPayService;
    @Resource
    private WeChatPayServer weChatPayServer;

    @Resource
    private UserShopMapper userShopMapper;

    @Override
    public DataResult generateOrder(YxStoreCart yxStoreCart, Integer payType, Integer addrId) throws AlipayApiException {

        //首先加入购物车
        yxStoreCart.setAddTime(LocalDateTime.now());
        if (yxStoreCartService.save(yxStoreCart)) {
//            List<Integer> longs = Collections.singletonList(yxStoreCart.getId().intValue());
            return generateTrolleyOrder(yxStoreCart.getId().toString(), payType, addrId);
        }
        return new DataResult(300, "订单创建失败", null);
    }

    @Override
    public DataResult generateTrolleyOrder(String trolleyIds, Integer payType, Integer addrId) throws AlipayApiException {
        YxStoreOrder yxStoreOrder = new YxStoreOrder();
        yxStoreOrder.setAddTime(LocalDateTime.now());
        yxStoreOrder.setTotalPrice(BigDecimal.ZERO);
        yxStoreOrder.setTotalNum(0);
        yxStoreOrder.setFreightPrice(BigDecimal.ZERO);
        String[] a = trolleyIds.split(",");
        for (String string : a) {
            YxStoreCart yxStoreCart = yxStoreCartService.getById(string);
            YxStoreProduct storeProduct = yxStoreProductService.getById(yxStoreCart.getProductId());
            YxStoreProductAttrValue yxStoreProductAttrValue = yxStoreProductAttrValueMapper.
                    selectOne(new QueryWrapper<YxStoreProductAttrValue>().eq("product_id", yxStoreCart.getProductId())
                            .eq("suk", yxStoreCart.getProductAttrUnique()));
            if (storeProduct.getPostage() == null) {
                storeProduct.setPostage(BigDecimal.ZERO);
            }
            BigDecimal multiply = yxStoreProductAttrValue.getPrice().multiply(BigDecimal.valueOf(yxStoreCart.getCartNum()));
            BigDecimal total = multiply.add(storeProduct.getPostage());
            yxStoreOrder.setTotalPrice(yxStoreOrder.getTotalPrice().add(total));
            yxStoreOrder.setTotalNum(yxStoreOrder.getTotalNum() + yxStoreCart.getCartNum());

            yxStoreOrder.setFreightPrice(yxStoreOrder.getFreightPrice().add(storeProduct.getPostage()));
            yxStoreOrder.setUid(yxStoreCart.getUid());
            //商戶
            QueryWrapper<UserShop> userShopQueryWrapper = new QueryWrapper<>();
            userShopQueryWrapper.eq("id", storeProduct.getMerId());
            UserShop userShop = userShopMapper.selectOne(userShopQueryWrapper);
            yxStoreOrder.setMerId(userShop.getId().intValue());
        }
        yxStoreOrder.setCartId(trolleyIds);
        String orderId = WorkIdUtils.generateOrderId();
        yxStoreOrder.setOrderId(orderId);
        YxUserAddress userAddressInfo = yxUserAddressService.getById(addrId);
        yxStoreOrder.setRealName(userAddressInfo.getRealName());
        yxStoreOrder.setUserPhone(userAddressInfo.getPhone());
        yxStoreOrder.setUserAddress(JSON.toJSONString(userAddressInfo));
        if (this.save(yxStoreOrder)) {
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("orderInfo", this.getById(yxStoreOrder.getId()));
            String cartId = yxStoreOrder.getCartId();
            switch (payType) {
                case 0://余额
                    break;
                case 1://支付宝
                    return aliPayService.order(yxStoreOrder.getId().toString(), yxStoreOrder.getUid());
                case 2:
                    return weChatPayServer.order(yxStoreOrder.getId().toString(), yxStoreOrder.getUid(), null, null);
            }
            resultMap.put("goodsInfo", yxStoreCartMapper.selectList(new QueryWrapper<YxStoreCart>().in("id", cartId)));
            return new DataResult(200, "订单创建成功", resultMap);
        }
        return new DataResult(300, "订单创建失败", null);
    }

    @Override
    public int updateYxStoreOrders(YxStoreOrder yxStoreOrder) {
        return yxStoreOrderMapper.updateById(yxStoreOrder);
    }

    @Override
    public DataResult inquiryLogistics(String orderId) {

        YxStoreOrder yxStoreOrderInfo = this.getOne(new QueryWrapper<YxStoreOrder>().eq("order_id", orderId));
        if (yxStoreOrderInfo != null) {
            String deliveryId = yxStoreOrderInfo.getDeliveryId();
            try {
                if (StringUtils.isNotBlank(deliveryId)) {
                    KdApiOrderDistinguish api = new KdApiOrderDistinguish();
                    String orderTracesByJson = api.getOrderTracesByJson(deliveryId);
                    JSONArray shippers = JSON.parseObject(orderTracesByJson).getJSONArray("Shippers");
                    if (shippers != null) {
                        String shipperCode = JSON.parseObject(shippers.get(0).toString()).get("ShipperCode").toString();
                        KdniaoTrackQueryAPI kdniaoTrackQueryAPI = new KdniaoTrackQueryAPI();
                        String orderTracesByJson1 = kdniaoTrackQueryAPI.getOrderTracesByJson(shipperCode, deliveryId);
                        return new DataResult(200, "查询成功", orderTracesByJson1);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new DataResult(200, "暂无物流记录", null);
    }
}
